<template>

	<view class="container b-f">

		<!-- 头部背景图 -->
		<view class="dealer-bg">
			<image class="image" mode="widthFix" :src="background"></image>
		</view>

		<!-- 填写申请信息 -->
		<view class="dis-flex flex-dir-column flex-y-center">
			<view class="widget-form b-f m-top20 dis-flex flex-dir-column">
				<view class="form-title f-30">{{ words.title.value }}</view>
				<view class="form-box dis-flex flex-dir-column">
					<form @submit="handleSubmit">
						<view class="form-field dis-flex flex-y-center">
							<view class="field-label">邀请人</view>
							<view class="field-input">
								<text>{{ sceneName ? sceneName : '平台' }}（请核对）</text>
							</view>
						</view>
						<view class="form-field dis-flex flex-y-center">
							<view class="field-label">姓名</view>
							<view class="field-input flex-box">
								<input class="input" name="name" placeholder="请输入真实姓名"></input>
							</view>
						</view>
						<view class="form-field dis-flex flex-y-center">
							<view class="field-label">手机号</view>
							<view class="field-input flex-box">
								<input class="input" name="mobile" placeholder="请输入手机号"></input>
							</view>
						</view>

						<view class="form-field dis-flex flex-y-center">
							<view class="field-label">代理等级</view>
							<view class="field-input">
								<picker mode="selector" :range="member_level" @change="bindPickerChange">
									<view class="picker">
										当前选择：{{ selectedValue || '请选择' }}
									</view>
								</picker>
							</view>
						</view>

						<view class="form-field-checkbox dis-flex flex-y-center" >
			  <view class="field-label">授权商品</view>
			  <view class="field-input">
          <checkbox-group class="uni-list"  name="accredit_goods">
            <view span="4" v-for="(item, index) in authorizeGoods" :key="index">
                      <checkbox :value="item.goods_id"   />{{ item.goods_name}}
                    </view>
            
             
				</checkbox-group>
			  </view>
			</view>

						<view class="form-field dis-flex flex-y-center"   style="margin-bottom:107px;">
							<view class="field-label">付款凭证</view>
							<view class="field-input">
								<view class="image-list">
									<view class="image-preview">
										<text class="image-delete iconfont icon-shanchu" @click="deleteImage(1)"></text>
										<image class="image" mode="aspectFill" :src="imgpath"></image>
									</view>
									<view class="image-picker" @click="chooseImage(1)">
										<text class="choose-icon iconfont icon-camera"></text>
										<text class="choose-text">上传图片</text>
									</view>
								</view>

							</view>
						</view>

						  

						<!-- 图片列表 -->

						<!-- 申请协议 -->
						<view class="form-license dis-flex flex-x-center flex-y-center">
							<view class="license-radio dis-flex flex-y-center" @click="isRead = !isRead">
								<text class="license-icon f-38 iconfont icon-radio"
									:class="[isRead ? 'c-violet' : 'col-bb']"></text>
								<text class="f-28 col-80">我已阅读并了解</text>
							</view>
							<text @click="handleShowLicense()" class="f-28 c-violet">【{{ words.license.value }}】</text>
						</view>
						<!-- 立即申请 -->
						<view class="form-submit dis-flex flex-x-center">
							<button formType="submit" :disabled="disabled">{{ words.submit.value }}</button>
						</view>
					</form>
				</view>
			</view>
		</view>

		<!-- 入驻协议弹窗 -->
		<u-modal v-model="showLicense" title="申请协议">
			<scroll-view class="pops-content" :scroll-y="true">
				<text>{{ license }}</text>
			</scroll-view>
		</u-modal>

	</view>
</template>

<script>
import * as ApplyApi from '@/api/dealer/apply'
import SettingModel from '@/common/model/dealer/Setting'

import * as UploadApi from '@/api/upload'
import {
	checkLogin
} from '@/core/app'
import * as Api from '@/api/dealer'
import * as UserApi from '@/api/user'

import ConfigApi from '@/config'
export default {
	data() {
		return {
			imgpath: '',
			fimage: {
				path: ''
			},
			// 正在加载
			isLoading: true,
			// 当前是否为分销商
			isDealer: undefined,
			// 当前是否在申请中
			isApplying: undefined,
			// 推荐人昵称
			refereeName: undefined,
			// 文字设置
			words: undefined,
			// 背景图
			background: undefined,
			// 入驻协议
			license: undefined,
			// 入驻协议阅读状态
			isRead: false,
			// 显示入驻协议弹窗
			showLicense: false,
			// 按钮禁用
			disabled: false,
			dealer_id: 0, //推荐人id
			sceneName: '', //推荐人真实姓名
			is_card: false, //身份证是否上传
			is_recharge: false, //是否已选择充值套餐
			// 是否已登录
			isLogin: false,
			sceneUid: 0,
			member_level: [],
			selectedValue: '经销商',
			selectedValueid: 0,
			  // 已授权商品
			  authorizeGoods: [],
      
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {

		if (options && options.dealer_id) {
			this.dealer_id = options.dealer_id;
			this.sceneName = options.sceneName
		}
		this.getSetting()
		this.getApplyStatus()
	},
	onShow() {
		// this.isLogin = checkLogin()
		// if(this.isLogin === false){
		// 	this.$navTo('pages/login/index',{},'redirectTo');
		// }

		if (uni.getStorageSync('is_card')) {
			this.is_card = true;
		} else {
			this.is_card = false;
		}

		if (uni.getStorageSync('is_recharge')) {
			this.is_recharge = true;
		} else {
			this.is_recharge = false;
		}
	},
	onBackPress() {
		console.log('返回!')
		return true;
	},

	methods: {
		// 选择图片
		chooseImage(index) {
			const app = this
			// 选择图片
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success({
					tempFiles
				}) {
					app.imgpath = tempFiles[0]['path'];
					console.log();
				}
			});
		},

		// 删除图片
		deleteImage(index) {
			this.imgpath = '';
		},


		// 当下拉选择框的值改变时触发  
		bindPickerChange: function (e) {
			this.selectedValue = this.member_level[e.detail.value];
			this.selectedValueid = e.detail.value;
			console.log('picker发送选择改变，携带值为', e.detail.value);
		},

		//选择充值套餐
		toRecharge() {
			this.$navTo('pages/wallet/recharge/index', {
				is_apply: true
			});
		},
		//选择身份证
		toCard() {
			this.$navTo('pages/dealer/card');
		},

		// 获取分销设置
		getSetting() {
			const app = this
			SettingModel.data()
				.then(setting => {
					app.authorizeGoods = setting.accredit_goods
					// 赋值属性
					app.words = setting.words.apply.words
					app.background = setting.background.apply
					app.license = setting.license.license
					app.member_level = setting.member_level
					console.log(app.member_level)
					app.selectedValue = app.member_level[0];
					// 设置当前页面标题
					app.setPageTitle(setting.words.apply.title)
				})
		},

		// 分销商申请状态
		getApplyStatus() {
			const app = this
			app.isLoading = true

			app.isApplying = undefined;
			//      ApplyApi.status()
			//        .then(result => {
			//          const data = result.data
			//          app.isDealer = data.isDealer
			//          app.isApplying = data.isApplying
			//          // app.refereeName = data.refereeName
			// //如果是分销商
			// if(app.isDealer == true){
			// 	this.$navTo('pages/dealer/index',{},'redirectTo');
			// }
			//        })
			//        .finally(() => app.isLoading = false)
		},

		// 设置当前页面标题
		setPageTitle(title) {
			uni.setNavigationBarTitle({
				title: title.value
			})
		},

		// 切换支付选项
		handleChecked(value) {
			this.payment = value
		},

		// 显示入驻协议弹窗
		handleShowLicense() {
			this.showLicense = true
		},
		// 上传图片
		uploadFile() {
			const app = this

			// 整理上传文件路径
			const files = []

			// 批量上传
			UploadApi.image(app.imgpath).then(fileIds => {
				// resolve(fileIds)
			})
		},
		//去商城逛逛
		toIndex() {

			//判断是否有权限查看首页
			UserApi.info()
				.then(result => {
					const userInfo = result.data.userInfo;

					if (userInfo.is_check != 1) {
						//没审核过
						uni.showToast({
							title: '请您耐心等待后台审核',
							icon: 'none',
							duration: 1500
						})
						return false;
					} else {
						this.$navTo('pages/index/index');
					}
				})

		},

		// 表单提交
		handleSubmit({
			detail
		}) {
			const app = this
			if (!app.imgpath) {
				uni.showToast({
					title: '请提交付款凭证'
				})
				return;
			}

			uni.showLoading({ title: '加载中' })
			uni.uploadFile({
				url: ConfigApi.apiUrl + 'upload/image_prove',
				filePath: app.imgpath,
				name: 'file',
				formData: {
					'user_id': 0,
				},
				success: (uploadFileRes) => {

					if (uploadFileRes.statusCode == 200) {

						console.log('uploadFileRes', JSON.parse(uploadFileRes.data).message)
						if (JSON.parse(uploadFileRes.data).message == '图片上传失败：图片文件大小不能超出2MB') {


							uni.hideLoading()
							uni.showToast({
								title: '图片上传失败,图片文件大小不能超出2MB'
							})
							return;
						}

						detail.value.pz_image = JSON.parse(uploadFileRes.data).message;

						detail.value.selectedValueid = app.selectedValueid;
						detail.value.dealer_id = app.dealer_id;
						detail.value.is_card = app.is_card;
						// detail.value.is_recharge = app.is_recharge;
						// detail.value.card_z = uni.getStorageSync('card') ? uni.getStorageSync('card')[0] : '';
						// detail.value.card_f = uni.getStorageSync('card') ? uni.getStorageSync('card')[1] : '';

						detail.value.dealer = 1; // 是从分销商页面过来的，免登录注册
						// 表单验证
						if (!app.onValidation(detail.value)) {
							return false
						}

						// 确认提交，自动注册会员信息，申请成为分销商
						// app.disabled = true

						// https://dl.helasjewellery.com/index.php?s=/api/index/zhuces

						ApplyApi.zcsubmit({
							form: detail.value
						})
							.then(result => {

								if (result.message != '分销商申请已提交') {
									if (result.message == '手机号已存在,等待审核') {
										// 跳转
										app.$toast('正在审核中')
										setTimeout(function () {
											app.$navTo('pages/dealer/applyabcsh');
										}, 1000)

										return;
									} else if (result.message == '手机号已存在,请登录') {

										// 跳转
										app.$toast('请登录')
										setTimeout(function () {
											app.$navTo('pages/login/index');
										}, 1000)
									}
									// 跳转
									app.$toast(result.message)
									return;
								}


								uni.hideLoading()
								app.$toast('提交申请成功!')
								//申请已提交，删除缓存，验证登录
								uni.removeStorageSync('sceneUid');
								uni.removeStorageSync('card');
								uni.removeStorageSync('is_card');
								uni.removeStorageSync('is_recharge');

								// this.isLogin = checkLogin()

								this.$navTo('pages/dealer/applyabcsh');
								// setTimeout(() => uni.navigateBack(1), 1200)
								// this.getApplyStatus();
								// setTimeout(() => this.$navTo('pages/dealer/apply',{},'redirectTo'), 1200)

							})

					} else {
						console.log('上传失败', uploadFileRes);
						return;
					}
				},

			});



		},

		// 表单验证
		onValidation(data) {
			const app = this
			// 验证可提现佣金
			if (!data.name) {
				app.$error('请填写姓名')
				return false
			}
			// 验证手机号
			if (!/^\+?\d[\d -]{8,12}\d/.test(data.mobile)) {
				app.$error('手机号格式不正确')
				return false
			}
			if (!data.mobile) {
				app.$error('手机号不能为空')
				return false
			}
			// if (!data.is_card) {
			// 	app.$error('请上传身份证')
			// 	return false
			// }
			// if (!data.is_recharge) {
			// 	app.$error('请选择充值套餐')
			// 	return false
			// }
			// 验证是否阅读协议
			if (!app.isRead) {
				app.$error('请先阅读分销商申请协议')
				return false
			}
			return true
		},

	}
}
</script>

<style>
page {
	background: #fff;
}
</style>
<style lang="scss" scoped>
.image-list {
	padding: 0 9px;
	margin-top: 75px;
	margin-bottom: -9px;
	position: relative;

	&:after {
		clear: both;
		content: " ";
		display: table;
	}

	.image {
		display: block;
		width: 100%;
		height: 100%;
	}

	.image-picker,
	.image-preview {
		width: 184rpx;
		height: 184rpx;
		margin-right: 30rpx;
		margin-bottom: 30rpx;
		float: left;

		&:nth-child(3n+0) {
			margin-right: 0;
		}
	}

	.image-picker {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border: 1rpx dashed #ccc;
		color: #ccc;

		.choose-icon {
			font-size: 48rpx;
			margin-bottom: 6rpx;
		}

		.choose-text {
			font-size: 24rpx;
		}
	}

	.image-preview {
		position: absolute;
		right: -105px;
		top: -1px;

		.image-delete {
			position: absolute;
			top: -15rpx;
			right: -15rpx;
			height: 42rpx;
			width: 42rpx;
			background: rgba(0, 0, 0, 0.64);
			border-radius: 50%;
			color: #fff;
			font-weight: bolder;
			font-size: 22rpx;
			z-index: 10;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}

/* 你可以在这里添加一些样式来美化你的picker */
.picker {
	padding: 10px;
	background-color: #f8f8f8;
	border: 1px solid #ddd;
	border-radius: 5px;
}

.c-violet {
	color: #786cff;
}

.col-80 {
	color: #808080;
}

.col-bb {
	color: #bbb;
}

.f-38 {
	font-size: 38rpx;
}

.dealer-bg {
	.image {
		width: 100%;
	}
}

.widget-form {
	position: relative;
	width: 700rpx;
	box-sizing: border-box;
	box-shadow: 0 1rpx 20rpx rgba(0, 0, 0, 0.21);
	border-radius: 12rpx;
	margin-top: -80rpx;

	.form-title {
		padding: 0 40rpx;
		height: 90rpx;
		border-bottom: 1rpx solid #e7e7e7;
		display: flex;
		align-items: center;
	}

	.form-box {
		padding: 40rpx 35rpx;

		.form-field {
			height: 80rpx;
			margin-bottom: 24rpx;
			padding: 10rpx 28rpx;
			background-color: #f9f9f9;
			box-sizing: border-box;
			font-size: 28rpx;

			.field-label {
				width: 130rpx;
				color: #808080;
			}

			.input {
				font-size: 28rpx;
			}
		}
	}
}

.form-license {
	.license-icon {
		margin-right: 12rpx;
	}
}

.form-submit {
	margin-top: 40rpx;

	button {
		font-size: 30rpx;
		background: #786cff;
		border: 1rpx solid #786cff;
		color: white;
		border-radius: 50rpx;
		padding: 0 120rpx;

		&[disabled] {
			background: #8e84fc;
			border-color: #8e84fc;
			color: white;
		}
	}

}

// 申请协议
.pops-content {
	padding: 30rpx 48rpx;
	font-size: 28rpx;
	line-height: 50rpx;
	text-align: left;
	color: #606266;
	min-height: 320rpx;
	max-height: 640rpx;
	box-sizing: border-box;
}

// 等待审核
.dealer-boot {
	padding: 10rpx 30rpx;
	margin-top: 80rpx;

	.msg__icon {
		font-size: 120rpx;
		color: #8e84fc;
	}

	.boot__submit {
		margin-top: 60rpx;
	}
}

.form-field-checkbox { 
        margin-bottom: 24rpx;
        padding: 10rpx 28rpx;
        background-color: #f9f9f9;
        box-sizing: border-box;
        font-size: 28rpx;

        .field-label {
          width:160rpx;
          color: #808080;
        }

        .input {
          font-size: 28rpx;
        }
      }
</style>